import os
import uuid


from django.db.models.fields import return_None
from django.shortcuts import render, redirect,reverse

from App.models import UserModel, PhotoModel
from DjangoProjectStatic import settings


# Create your views here.


def index(request):
    return render(request, 'index.html')

def index2(request):
    return render(request, 'index2.html')

def upload1(request):
    if request.method == 'GET':
        return render(request, 'upload1.html')
    elif request.method == 'POST':
        uname = request.POST.get('uname')
        icon = request.FILES.get('icon')
        # print(uname, icon)
        # print(type(icon))
        print(icon.name)
        print(os.path.splitext(icon.name)[-1])
        # 原图片名称，尽量不用
        # file_name = icon.name
    #     1.分段写入文件
        file_name = gen_uuid_name() + os.path.splitext(icon.name)[-1]
        file_path = os.path.join(settings.MEDIA_ROOT, file_name)

        with open(file_path, 'ab') as f:
            for part in icon.chunks():
                f.write(part)
                f.flush()

        # 2.文件路径保存到数据库

        user = UserModel()
        user.name = uname
        user.icon = 'uploads/' + file_name
        user.save()

    return redirect(reverse('showicon'))

# 通过UUID来得到唯一的图片名称
def gen_uuid_name():

    return str(uuid.uuid4())

def showicon(request):
    user = UserModel.objects.get(pk=1)
    return  render(request, 'showicon.html', {"user":user})

def upload2(request):
    if request.method == 'GET':
        return render(request, 'upload2.html')

    elif request.method == 'POST':
        uname = request.POST.get('uname')
        imgs = request.FILES.getlist('imgs')

        # print(uname, imgs)
    for img in imgs:

        file_name = gen_uuid_name() + os.path.splitext(img.name)[-1]
        file_path = os.path.join(settings.MEDIA_ROOT, file_name)
        with open(file_path, 'ab') as f:
            for part in img.chunks():
                f.write(part)
                f.flush()

        # 保存到数据库
        photo = PhotoModel()
        photo.img = 'uploads/' + file_name
        photo.user = UserModel.objects.filter(name=uname).first() # 有这个用户才能查询到
        photo.save()


    return redirect(reverse('showicon'))